package org.wheel.plugins.toolkit.sql.page.impl;

import cn.hutool.core.util.StrUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.JdbcNamedParameter;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.GreaterThan;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.wheel.plugins.toolkit.sql.page.PaginationStrategy;

/**
 * 游标分页策略 – WHERE id > :lastId
 */
public class CursorPaginationStrategy implements PaginationStrategy {

    @Override
    public String generatePaginationQuery(String originalSql, long pageNo, long pageSize) {
        // 直接返回：原 SQL + WHERE id > :lastId ORDER BY id LIMIT limit
        return StrUtil.format("{} WHERE id > :lastId ORDER BY id LIMIT {}", originalSql, pageSize);
    }

    public void apply(PlainSelect select, long lastId) {
        GreaterThan gt = new GreaterThan();
        gt.setLeftExpression(new Column("id"));
        gt.setRightExpression(new JdbcNamedParameter("lastId"));
        Expression where = select.getWhere();
        if (where != null) {
            select.setWhere(new AndExpression(where, gt));
        } else {
            select.setWhere(gt);
        }
    }
}